#include "mp3item.h"
#include <QErrorMessage>

// --------------- //
// CLASS : Mp3Item //
// --------------- //

//Constructor
Mp3Item::Mp3Item(QString name, const QUrl& url, int host, QSettings* settings):
        BlogItem(name, url, settings),
        _host(host),
        _downloadingStatus(Mp3Item::notDownloaded)
{
}

//Constructor from XML
Mp3Item::Mp3Item(const QDomElement& elt, QSettings* settings):
        BlogItem(elt.attribute("name"),
                 QUrl(elt.attribute("url")),
                 settings),
        _host(elt.attribute("host").toInt()),
        _downloadingStatus(elt.attribute("status").toInt())
{
}

//Default processing method (download)
void Mp3Item::defaultProcessing()
{
    this->download();
}

//Download method
void Mp3Item::download()
{
    setDownloadingStatus(downloading);
    switch(_host)
    {
        case Mp3Item::hostedDirectly:
        this->downloadDirect();
        break;

        case Mp3Item::hostedOnZippyShare:
        this->downloadZippyshare();
        break;
    }
}

//Getters / Setters
int Mp3Item::getDownloadingStatus() const
{
    return this->_downloadingStatus;
}

void Mp3Item::setDownloadingStatus(int status)
{
    this->_downloadingStatus = status;
}

QDate Mp3Item::getDatePosted() const
{
    return this->_datePosted;
}

//To XML
QDomElement Mp3Item::toDomElt()
{
    QDomElement elt = QDomElement();
    elt.setTagName("MP3");
    elt.setAttribute("name",_name);
    elt.setAttribute("url",_url.toString());
    elt.setAttribute("host",_host);
    elt.setAttribute("status",_downloadingStatus);

    return elt;
}

//Download (direct)
void Mp3Item::downloadDirect()
{
    _downloader = new RemoteFileDownloader(_url,QDir(_settings->value("downloadDir",QDir::homePath()).toString()),_name);


}

//Get download directory
QDir Mp3Item::getDownloadDir() const
{
    return QDir(_settings->value("downloadDir",QDir::homePath()).toString());
}

//Download (hosted in zippyshare)
void Mp3Item::downloadZippyshare()
{
    QErrorMessage::qtHandler()->showMessage("Zippyshare hosted songs are temporarly not supported");
    setDownloadingStatus(downloadError);
}

Mp3Downloader::Mp3Downloader(const Mp3Item* const item):
        RemoteFileDownloader(item->getUrl(),item->getDownloadDir(),item->getName())
{
    connect(this,SIGNAL(downloadFinished()),this,SLOT(downloadFinished()));
}

void Mp3Downloader::downloadFinished()
{
    _mp3Item->setDownloadingStatus(Mp3Item::downloaded);
}

